<template>
	<div>
		<div class="container">
			<div class="toolbar">
				<a-form ref="searchRef" layout="inline" :model="searchState" @finish="loading = true; initData()">
					<a-form-item label="公司筛选">
						<a-select v-model:value="searchState.company_id" :show-search="true" placeholder="请选择项目" :options="companyOptions" option-filter-prop="label" allow-clear></a-select>
					</a-form-item>
					<a-form-item label="项目筛选">
						<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" allow-clear></a-select>
					</a-form-item>
					<a-form-item label="筛选字段">
						<a-select v-model:value="searchState.args" style="min-width: 100px" mode="tags" :show-search="true" :options="argOptions" option-filter-prop="label" allow-clear></a-select>
					</a-form-item>
					<a-form-item>
						<a-space>
							<a-button type="primary" html-type="submit">
								<search-outlined />搜索
							</a-button>
						</a-space>
					</a-form-item>
				</a-form>
			</div>
			<div class="mt-2" style="overflow-y: hidden">
				<a-table :columns="innerColumns" :scroll="tableScroll" children-column-name="children" :default-expand-all-rows="false" :data-source="pageSources" :pagination="false" :loading="loading">
					<template #bodyCell="{ column, record, index }">
						<template v-if="column.dataIndex === 'operation'">
							<a-space>
								<a-button v-permission="194" type="link" @click="edit(record)">
									<edit-outlined />编辑
								</a-button>
							</a-space>
						</template>
						<template v-if="column.dataIndex === 'project_id'">
							<a-space>
								<a-select v-model:value="pageSources[index].project_id" :options="projectOptions" option-filter-prop="label" disabled></a-select>
							</a-space>
						</template>
						<template v-if="column.dataIndex === 'company_id' && pageSources[index].company_id">
							<a-space>
								<a-select v-model:value="pageSources[index].company_id" :options="companyOptions" option-filter-prop="label" disabled></a-select>
							</a-space>
						</template>
					</template>
				</a-table>
			</div>
		</div>
		<a-modal v-model:visible="visible" :width="500" :title="modalTitle" class="modal" @ok="save">
			<a-form ref="formRef" :model="formState" v-bind="{ labelCol: { style: { width: '100px' } } }">
				<table cellspacing="0" cellpadding="0" style="width: 100%;">
					<tr>
						<td>
							<a-form-item label="城市公司" name="company_id">
								<a-row :gutter="10">
									<a-col :span="24">
										<a-select v-model:value="formState.company_id" :show-search="true" placeholder="请选择项目" :options="companyOptions" option-filter-prop="label" disabled></a-select>
									</a-col>
								</a-row>
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="项目名称" name="project_id" :rules="{ required: true, message: '请选择项目' }">
								<a-row :gutter="10">
									<a-col :span="24">
										<a-select v-model:value="formState.project_id" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" disabled></a-select>
									</a-col>
								</a-row>
							</a-form-item>
						</td>
					</tr>
					<tr v-for="column of innerColumns.filter(item =>!['project_id', 'company_id', 'company_name', 'operation', 'index'].includes(item.dataIndex))" :key="column.dataIndex">
						<td>
							<a-form-item :label="column.title" :name="column.dataIndex">
								<a-row :gutter="10">
									<a-col :span="24">
										<a-input v-model:value="formState[column.dataIndex]" />
									</a-col>
								</a-row>
							</a-form-item>
						</td>
					</tr>
				</table>
			</a-form>
			<template #footer>
				<a-button type="plain" @click="visible = false">取消</a-button>
				<a-button type="primary" @click="save">确定</a-button>
			</template>
		</a-modal>
	</div>
</template>

<script setup>
import { usePagination } from "vue-request";
import { post } from "../utils/index.js";
import { computed, getCurrentInstance, reactive, ref } from "vue";

import { EditOutlined } from "@ant-design/icons-vue";
const searchRef = ref();
const searchState = reactive({
	args: []
});
const visible = ref(false);
const optType = ref(1); // 1新增 2编辑
const formState = ref({});
const formRef = ref();
const pageSources = ref([]);
const loading = ref(false);
const { proxy } = getCurrentInstance();
const projectOptions = ref([]);
const companyOptions = ref([]);
const argOptions = ref([]);
const initProjects = new Promise((resolve, reject) => {
	post("department/projects?type=3").then(({ data }) => {
		projectOptions.value = data.map(d => {
			return {
				value: d.id,
				label: d.name,
				parent_ids: d.parent_ids
			};
		});
		resolve();
	});
});
const initCompany = new Promise((resolve, reject) => {
	post("department/projects?type=2", {
		parent_ids: JSON.stringify([78, 24])
	}).then(({ data }) => {
		companyOptions.value = data.map(d => {
			return {
				value: d.id,
				label: d.name
			};
		});
		resolve();
	});
});
Promise.all([initProjects, initCompany]).then(() => {
	initData();
});

const columns = ref([]);
const innerColumns = computed(() => {
	if (!searchState.args.length) {
		return columns.value;
	}
	return columns.value.filter(item => {
		return item.fixed || searchState.args.includes(item.dataIndex);
	});
});
post("data/all").then(({ data }) => {
	for (const d of data) {
		if (!d.show) continue;
		const item = {
			title: d.data_name,
			dataIndex: d.data_key,
			sorter: false,
			width: 180,
			ellipsis: true
		};
		if (d.read_only) {
			item.fixed = "left";
		} else {
			argOptions.value.push({
				value: d.data_key,
				label: d.data_name
			});
		}
		if (d.data_key === "index") {
			item.width = 80;
			item.customRender = ({ text, record, index, column }) => {
				return index + 1;
			};
		}
		columns.value.push(item);
	}
	columns.value.push({
		title: "操作",
		dataIndex: "operation",
		sorter: false,
		fixed: "right",
		width: 100,
		align: "center"
	});
});
const tableScroll = computed(() => ({
	x: document.documentElement.clientWidth - 650
}));

const modalTitle = computed(() => {
	return `${optType.value === 1 ? "新增" : "修改"}数据`;
});
const initData = () => {
	loading.value = true;
	const searchProjectId = searchState.project_id;
	post("dataRecords")
		.then(({ data }) => {
			const data2Project_id = data.reduce((target, item) => {
				target[item.record.project_id] = item;
				return target;
			}, {});
			const list = [];
			for (const projectOption of projectOptions.value) {
				if (searchProjectId && searchProjectId !== projectOption.value) continue;
				const item = data2Project_id[projectOption.value];
				if (item) {
					if (searchState.company_id && searchState.company_id !== item.record.company_id) continue;
					list.push({
						...item.record,
						id: item.id
					});
				} else {
					let companyId;
					const projectParentIds = projectOption.parent_ids.split(",").map(id => parseInt(id));
					if (searchState.company_id && !projectParentIds.includes(searchState.company_id)) continue;
					for (const company of companyOptions.value) {
						if (projectParentIds.includes(company.value)) {
							companyId = company.value;
							break;
						}
					}
					list.push({
						project_id: projectOption.value,
						company_id: companyId
					});
				}
			}
			pageSources.value = list;
		})
		.finally(() => {
			loading.value = false;
		});
};
const add = () => {
	optType.value = 1;
	formRef.value?.clearValidate();
	visible.value = true;
	formState.value = {};
};

const edit = item => {
	optType.value = 2;
	visible.value = true;
	formState.value = { ...item };
};

const save = () => {
	const params = {
		...(formState.value.id ? { id: formState.value.id } : {}),
		record: JSON.stringify(formState.value)
	};
	formRef.value.validate().then(() => {
		proxy.$message.destroy();
		post("dataRecords/save", params)
			.then(() => {
				proxy.$message.success("提交成功", 1);
				visible.value = false;
				initData();
			})
			.catch(err => {
				proxy.$message.error(err.message || err);
			});
	});
};
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}
</style>
<style>
.modal .ant-modal-body {
	overflow-y: auto;
	max-height: 300px; /* 设置自定义的高度 */
}
</style>
